/*
 * @(#)ContactPerson.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.contact.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.dcivision.contact.bean.ContactList;
import com.dcivision.contact.bean.ContactPerson;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.web.AbstractSearchForm;

/**
  ContactPersonDAObject.java

  This class is the data access bean for table "CONTACT_PERSON".

  @author           Jenny Li
  @company          DCIVision Limited
  @creation date    04/01/2005
  @version          $Revision: 1.20 $
*/

public class ContactPersonDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.20 $";

  public static final String TABLE_NAME = "CONTACT_PERSON";

  public ContactPersonDAObject(SessionContainer sessionContainer, Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("OWNER_ID");
    this.vecDBColumn.add("FIRST_NAME");
    this.vecDBColumn.add("LAST_NAME");
    this.vecDBColumn.add("PHONE_NO");
    this.vecDBColumn.add("MOBILE_NO");
    this.vecDBColumn.add("FAX_NO");
    this.vecDBColumn.add("EMAIL");
    this.vecDBColumn.add("REMARKS");
    this.vecDBColumn.add("TITLE");
    this.vecDBColumn.add("DEPARTMENT");
    this.vecDBColumn.add("PUBLIC_FLAG");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_ID, A.FIRST_NAME, A.LAST_NAME, A.PHONE_NO, A.MOBILE_NO, A.FAX_NO, A.EMAIL, A.REMARKS, A.TITLE, A.DEPARTMENT, A.PUBLIC_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   CONTACT_PERSON A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          ContactPerson tmpContactPerson = new ContactPerson();
          tmpContactPerson.setID(getResultSetInteger(rs, "ID"));
          tmpContactPerson.setOwnerID(getResultSetInteger(rs, "OWNER_ID"));
          tmpContactPerson.setFirstName(getResultSetString(rs, "FIRST_NAME"));
          tmpContactPerson.setLastName(getResultSetString(rs, "LAST_NAME"));
          tmpContactPerson.setPhoneNo(getResultSetString(rs, "PHONE_NO"));
          tmpContactPerson.setMobileNo(getResultSetString(rs, "MOBILE_NO"));
          tmpContactPerson.setFaxNo(getResultSetString(rs, "FAX_NO"));
          tmpContactPerson.setEmail(getResultSetString(rs, "EMAIL"));
          tmpContactPerson.setRemarks(getResultSetString(rs, "REMARKS"));
          tmpContactPerson.setTitle(getResultSetString(rs, "TITLE"));
          tmpContactPerson.setDepartment(getResultSetString(rs, "DEPARTMENT"));
          tmpContactPerson.setPublicFlag(getResultSetString(rs, "PUBLIC_FLAG"));
          tmpContactPerson.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpContactPerson.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpContactPerson.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpContactPerson.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpContactPerson.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpContactPerson.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpContactPerson.setCreatorName(UserInfoFactory.getUserFullName(tmpContactPerson.getCreatorID()));
          tmpContactPerson.setUpdaterName(UserInfoFactory.getUserFullName(tmpContactPerson.getUpdaterID()));
          return(tmpContactPerson);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized List getList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_ID, A.FIRST_NAME, A.LAST_NAME, A.PHONE_NO, A.MOBILE_NO, A.FAX_NO, A.EMAIL, A.REMARKS, A.TITLE, A.DEPARTMENT, A.PUBLIC_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   CONTACT_PERSON A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND (A.PUBLIC_FLAG=? OR (A.PUBLIC_FLAG=? AND A.OWNER_ID=? )) ");
        sqlStat.append(this.getIDFilterWhereClause("A"));

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, ContactList.SHARING_TYPE_PUB);
        this.setPrepareStatement(preStatCnt, 3, ContactList.SHARING_TYPE_PRI);
        this.setPrepareStatement(preStatCnt, 4, sessionContainer.getUserRecordID());
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 5, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, ContactList.SHARING_TYPE_PUB);
        this.setPrepareStatement(preStat, 3, ContactList.SHARING_TYPE_PRI);
        this.setPrepareStatement(preStat, 4, sessionContainer.getUserRecordID());
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 5, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          ContactPerson tmpContactPerson = new ContactPerson();
          tmpContactPerson.setID(getResultSetInteger(rs, "ID"));
          tmpContactPerson.setOwnerID(getResultSetInteger(rs, "OWNER_ID"));
          tmpContactPerson.setFirstName(getResultSetString(rs, "FIRST_NAME"));
          tmpContactPerson.setLastName(getResultSetString(rs, "LAST_NAME"));
          tmpContactPerson.setPhoneNo(getResultSetString(rs, "PHONE_NO"));
          tmpContactPerson.setMobileNo(getResultSetString(rs, "MOBILE_NO"));
          tmpContactPerson.setFaxNo(getResultSetString(rs, "FAX_NO"));
          tmpContactPerson.setEmail(getResultSetString(rs, "EMAIL"));
          tmpContactPerson.setRemarks(getResultSetString(rs, "REMARKS"));
          tmpContactPerson.setTitle(getResultSetString(rs, "TITLE"));
          tmpContactPerson.setDepartment(getResultSetString(rs, "DEPARTMENT"));
          tmpContactPerson.setPublicFlag(getResultSetString(rs, "PUBLIC_FLAG"));
          tmpContactPerson.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpContactPerson.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpContactPerson.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpContactPerson.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpContactPerson.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpContactPerson.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpContactPerson.setCreatorName(UserInfoFactory.getUserFullName(tmpContactPerson.getCreatorID()));
          tmpContactPerson.setUpdaterName(UserInfoFactory.getUserFullName(tmpContactPerson.getUpdaterID()));
          tmpContactPerson.setRecordCount(totalNumOfRecord);
          tmpContactPerson.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpContactPerson);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_ID, A.FIRST_NAME, A.LAST_NAME, A.PHONE_NO, A.MOBILE_NO, A.FAX_NO, A.EMAIL, A.REMARKS, A.TITLE, A.DEPARTMENT, A.PUBLIC_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   CONTACT_PERSON A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append(this.getIDFilterWhereClause("A"));

        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        while (rs.next()) {
          ContactPerson tmpContactPerson = new ContactPerson();
          tmpContactPerson.setID(getResultSetInteger(rs, "ID"));
          tmpContactPerson.setOwnerID(getResultSetInteger(rs, "OWNER_ID"));
          tmpContactPerson.setFirstName(getResultSetString(rs, "FIRST_NAME"));
          tmpContactPerson.setLastName(getResultSetString(rs, "LAST_NAME"));
          tmpContactPerson.setPhoneNo(getResultSetString(rs, "PHONE_NO"));
          tmpContactPerson.setMobileNo(getResultSetString(rs, "MOBILE_NO"));
          tmpContactPerson.setFaxNo(getResultSetString(rs, "FAX_NO"));
          tmpContactPerson.setEmail(getResultSetString(rs, "EMAIL"));
          tmpContactPerson.setRemarks(getResultSetString(rs, "REMARKS"));
          tmpContactPerson.setTitle(getResultSetString(rs, "TITLE"));
          tmpContactPerson.setDepartment(getResultSetString(rs, "DEPARTMENT"));
          tmpContactPerson.setPublicFlag(getResultSetString(rs, "PUBLIC_FLAG"));
          tmpContactPerson.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpContactPerson.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpContactPerson.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpContactPerson.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpContactPerson.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpContactPerson.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpContactPerson.setCreatorName(UserInfoFactory.getUserFullName(tmpContactPerson.getCreatorID()));
          tmpContactPerson.setUpdaterName(UserInfoFactory.getUserFullName(tmpContactPerson.getUpdaterID()));
          result.add(tmpContactPerson);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    ContactPerson tmpContactPerson = (ContactPerson)((ContactPerson)obj).clone();

    synchronized(dbConn) {
      try {
        Integer nextID = getNextPrimaryID();
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   CONTACT_PERSON(ID, OWNER_ID, FIRST_NAME, LAST_NAME, PHONE_NO, MOBILE_NO, FAX_NO, EMAIL, REMARKS, TITLE, DEPARTMENT, PUBLIC_FLAG, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, nextID);
        setPrepareStatement(preStat, 2, tmpContactPerson.getOwnerID());
        setPrepareStatement(preStat, 3, tmpContactPerson.getFirstName());
        setPrepareStatement(preStat, 4, tmpContactPerson.getLastName());
        setPrepareStatement(preStat, 5, tmpContactPerson.getPhoneNo());
        setPrepareStatement(preStat, 6, tmpContactPerson.getMobileNo());
        setPrepareStatement(preStat, 7, tmpContactPerson.getFaxNo());
        setPrepareStatement(preStat, 8, tmpContactPerson.getEmail());
        setPrepareStatement(preStat, 9, tmpContactPerson.getRemarks());
        setPrepareStatement(preStat, 10, tmpContactPerson.getTitle());
        setPrepareStatement(preStat, 11, tmpContactPerson.getDepartment());
        setPrepareStatement(preStat, 12, tmpContactPerson.getPublicFlag());
        setPrepareStatement(preStat, 13, GlobalConstant.RECORD_STATUS_ACTIVE);
        setPrepareStatement(preStat, 14, new Integer(0));
        setPrepareStatement(preStat, 15, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 16, currTime);
        setPrepareStatement(preStat, 17, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 18, currTime);
        preStat.executeUpdate();
        tmpContactPerson.setID(nextID);
        tmpContactPerson.setCreatorID(sessionContainer.getUserRecordID());
        tmpContactPerson.setCreateDate(currTime);
        tmpContactPerson.setUpdaterID(sessionContainer.getUserRecordID());
        tmpContactPerson.setUpdateDate(currTime);
        tmpContactPerson.setUpdateCount(new Integer(0));
        tmpContactPerson.setCreatorName(UserInfoFactory.getUserFullName(tmpContactPerson.getCreatorID()));
        tmpContactPerson.setUpdaterName(UserInfoFactory.getUserFullName(tmpContactPerson.getUpdaterID()));
        return(tmpContactPerson);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    ContactPerson tmpContactPerson = (ContactPerson)((ContactPerson)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE CONTACT_PERSON ");
        sqlStat.append("SET  OWNER_ID=?, FIRST_NAME=?, LAST_NAME=?, PHONE_NO=?, MOBILE_NO=?, FAX_NO=?, EMAIL=?, REMARKS=?, TITLE=?, DEPARTMENT=?, PUBLIC_FLAG=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpContactPerson.getOwnerID());
        setPrepareStatement(preStat, 2, tmpContactPerson.getFirstName());
        setPrepareStatement(preStat, 3, tmpContactPerson.getLastName());
        setPrepareStatement(preStat, 4, tmpContactPerson.getPhoneNo());
        setPrepareStatement(preStat, 5, tmpContactPerson.getMobileNo());
        setPrepareStatement(preStat, 6, tmpContactPerson.getFaxNo());
        setPrepareStatement(preStat, 7, tmpContactPerson.getEmail());
        setPrepareStatement(preStat, 8, tmpContactPerson.getRemarks());
        setPrepareStatement(preStat, 9, tmpContactPerson.getTitle());
        setPrepareStatement(preStat, 10, tmpContactPerson.getDepartment());
        setPrepareStatement(preStat, 11, tmpContactPerson.getPublicFlag());
        setPrepareStatement(preStat, 12, new Integer(tmpContactPerson.getUpdateCount().intValue() + 1));
        setPrepareStatement(preStat, 13, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 14, currTime);
        setPrepareStatement(preStat, 15, tmpContactPerson.getID());
        setPrepareStatement(preStat, 16, tmpContactPerson.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpContactPerson.setUpdaterID(sessionContainer.getUserRecordID());
          tmpContactPerson.setUpdateDate(currTime);
          tmpContactPerson.setUpdateCount(new Integer(tmpContactPerson.getUpdateCount().intValue() + 1));
          tmpContactPerson.setCreatorName(UserInfoFactory.getUserFullName(tmpContactPerson.getCreatorID()));
          tmpContactPerson.setUpdaterName(UserInfoFactory.getUserFullName(tmpContactPerson.getUpdaterID()));
          return(tmpContactPerson);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    ContactPerson tmpContactPerson = (ContactPerson)((ContactPerson)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   CONTACT_PERSON ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpContactPerson.getID());
        setPrepareStatement(preStat, 2, tmpContactPerson.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return(tmpContactPerson);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    ContactPerson tmpContactPerson = (ContactPerson)this.oldValue;

    if (tmpContactPerson != null) {
      oldValues.add(toAuditTrailValue(tmpContactPerson.getID()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getOwnerID()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getFirstName()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getLastName()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getPhoneNo()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getMobileNo()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getFaxNo()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getEmail()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getRemarks()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getTitle()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getDepartment()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getPublicFlag()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpContactPerson.getUpdateDate()));
    }

    tmpContactPerson = (ContactPerson)obj;
    if (tmpContactPerson != null) {
      newValues.add(toAuditTrailValue(tmpContactPerson.getID()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getOwnerID()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getFirstName()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getLastName()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getPhoneNo()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getMobileNo()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getFaxNo()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getEmail()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getRemarks()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getTitle()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getDepartment()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getPublicFlag()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpContactPerson.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/
  
  /**
   * get list by first name,last name,email for checking duplicated records.
   * @param firstName                
   * @param lastName
   * @param email
   * @return list
   * @throws ApplicationException
   */
  public synchronized List getListByFirstNameLastNameEmail(String firstName,String lastName,String email,String publicFlag) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_ID, A.FIRST_NAME, A.LAST_NAME, A.PHONE_NO, A.MOBILE_NO, A.FAX_NO, A.EMAIL, A.REMARKS, A.TITLE, A.DEPARTMENT, A.PUBLIC_FLAG, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   CONTACT_PERSON A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append("AND A.FIRST_NAME = ? AND A.LAST_NAME = ? AND A.EMAIL = ? ");
        if(ContactList.SHARING_TYPE_PUB.equals(publicFlag)){
          sqlStat.append("AND A.PUBLIC_FLAG = ? ");
        }else if(ContactList.SHARING_TYPE_PRI.equals(publicFlag)){
          sqlStat.append("AND A.PUBLIC_FLAG = ? AND A.OWNER_ID = ? ");
        }
        sqlStat.append(this.getIDFilterWhereClause("A"));

        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, firstName);
        this.setPrepareStatement(preStat, 3, lastName);
        this.setPrepareStatement(preStat, 4, email);
        if(ContactList.SHARING_TYPE_PUB.equals(publicFlag)){
          this.setPrepareStatement(preStat, 5, publicFlag);
        }else if(ContactList.SHARING_TYPE_PRI.equals(publicFlag)){
          this.setPrepareStatement(preStat, 5, publicFlag);
          this.setPrepareStatement(preStat, 6, sessionContainer.getUserRecordID());
        }
        
        rs = preStat.executeQuery();
        while (rs.next()) {
          ContactPerson tmpContactPerson = new ContactPerson();
          tmpContactPerson.setID(getResultSetInteger(rs, "ID"));
          tmpContactPerson.setOwnerID(getResultSetInteger(rs, "OWNER_ID"));
          tmpContactPerson.setFirstName(getResultSetString(rs, "FIRST_NAME"));
          tmpContactPerson.setLastName(getResultSetString(rs, "LAST_NAME"));
          tmpContactPerson.setPhoneNo(getResultSetString(rs, "PHONE_NO"));
          tmpContactPerson.setMobileNo(getResultSetString(rs, "MOBILE_NO"));
          tmpContactPerson.setFaxNo(getResultSetString(rs, "FAX_NO"));
          tmpContactPerson.setEmail(getResultSetString(rs, "EMAIL"));
          tmpContactPerson.setRemarks(getResultSetString(rs, "REMARKS"));
          tmpContactPerson.setTitle(getResultSetString(rs, "TITLE"));
          tmpContactPerson.setDepartment(getResultSetString(rs, "DEPARTMENT"));
          tmpContactPerson.setPublicFlag(getResultSetString(rs, "PUBLIC_FLAG"));
          tmpContactPerson.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpContactPerson.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpContactPerson.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpContactPerson.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpContactPerson.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpContactPerson.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpContactPerson.setCreatorName(UserInfoFactory.getUserFullName(tmpContactPerson.getCreatorID()));
          tmpContactPerson.setUpdaterName(UserInfoFactory.getUserFullName(tmpContactPerson.getUpdaterID()));
          result.add(tmpContactPerson);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }
  
}
